/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package iQuizzView;

import javax.bluetooth.*;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.bluetooth.BluetoothStateException;
import javax.bluetooth.DeviceClass;
import javax.bluetooth.DiscoveryAgent;
import javax.bluetooth.DiscoveryListener;
import javax.bluetooth.LocalDevice;
import javax.bluetooth.ServiceRecord;
import javax.bluetooth.UUID;
import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;
import javax.microedition.io.StreamConnectionNotifier;


/**
 * @author Etienne Parent-Jung Thomas Jouêtre
 */
public class PhoneNI implements DiscoveryListener,Runnable {

    /** Creates a new instance of ClientServer */
    UUID RFCOMM_UUID = null;
    private String m_ServerUrl = "btspp://localhost:" + RFCOMM_UUID + ";name=rfcommtest;authorize=true";
    private StreamConnection m_StrmConn = null;
    private LocalDevice m_LclDevice = null;
    private InputStream m_Input = null;
    private OutputStream m_Output = null;
    private StreamConnectionNotifier m_StrmNotf = null;
    public boolean m_bIsServer = false, m_bServerFound = false, m_bInitServer = false, m_bInitClient = false;
    private static String m_strUrl;
    private final String SEVER_RESPONSE = "RUN_THE_GAME", CLIENT_RESPONSE = "CLIENT_IS_READY";
    private DiscoveryAgent m_DscrAgent = null;
    private PhoneController cont;
    private Thread th;
    private boolean ready;
    /**
     *
     * @param isServer
     */
    public PhoneNI(){
        RFCOMM_UUID = new UUID(0x0003);
        
    }

    /**
     *
     * @param cont
     */
    public void setPhoneController(PhoneController cont) {
        this.cont = cont;
    initialize();
    }
    
    /**
     *
     */
    public void initialize(){
       //on lance la recherche des equipements bluetooth
        SearchAvailDevices();
//on créé ensuite notre thread
        if(cont.getStarted()==false)
        {
           th= new Thread(new PhoneNI());
            cont.setStarted(true);
        }
        
    }
public boolean getReady()
{return ready;}

public void setReady(boolean ready)
{this.ready=ready;}
    /**
     * Vote de l'utilisateur
     */
    public void vote(int vote){
      
            try
            {
                m_Output.write(vote);
            }
            catch (IOException ex)
            {
                ex.printStackTrace();
            }
        
    }

    /**
     *
     */
    public void connect(int mdp){
     try
            {
                m_Output.write(mdp);
            }
            catch (IOException ex)
            {
                ex.printStackTrace();
            }

    }

    /**
    * Called when service found during service search
    */
    public void servicesDiscovered(int transID, ServiceRecord[] records) {

        for (int i = 0; i < records.length; i++) {
            m_strUrl = records[i].getConnectionURL(ServiceRecord.AUTHENTICATE_ENCRYPT, false);

            System.out.println(m_strUrl);
            if (m_strUrl.startsWith("btspp")) //we have found our service protocol
            {
                m_bServerFound = true;
                m_bInitClient = true;
                break;
            }

        }
    }

    /**
     * Called when device is found during inquiry
     */
    public void deviceDiscovered(RemoteDevice btDevice, DeviceClass cod) {

        try {
            // Get Device Info
            System.out.println("Device Discovered");
            System.out.println("Major Device Class: " + cod.getMajorDeviceClass() + " Minor Device Class: " + cod.getMinorDeviceClass());
            System.out.println("Bluetooth Address: " + btDevice.getBluetoothAddress());
            System.out.println("Bluetooth Friendly Name: " + btDevice.getFriendlyName(true));

            // Search for Services
            UUID uuidSet[] = new UUID[1];
          //  uuidSet[0] = RFCOMM_UUID;
            int searchID = m_DscrAgent.searchServices(null, uuidSet, btDevice, this);
        } catch (Exception e) {
            System.out.println("Device Discovered Error: " + e);
        }


    }

    /**
     *
     * @param discType
     */
    public void inquiryCompleted(int discType) {
        System.out.println("InquiryCompleted");

    }

    /**
     * called when service search gets complete
     */
    public void serviceSearchCompleted(int transID, int respCode) {
        if (m_bServerFound) {
            try {   //lets the communication start by setting the url and send client reponse

                m_StrmConn = (StreamConnection) Connector.open(m_strUrl);

                m_Output = m_StrmConn.openOutputStream();
                m_Input = m_StrmConn.openInputStream();
                th.start();
              /*  m_Output.write(CLIENT_RESPONSE.length());
                m_Output.write(CLIENT_RESPONSE.getBytes());*/

                cont.getGui().write("serviceSearchCompleted");
                this.setReady(true);
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }    
        
    /**
     *
     */
    public void SearchAvailDevices() {

        try {
            //First get the local device and obtain the discovery agent.
            m_LclDevice = LocalDevice.getLocalDevice();
     } catch (BluetoothStateException ex) {
          //  cont.getGui().write("Problem  the local devices");
            ex.printStackTrace();
        }

            m_DscrAgent = m_LclDevice.getDiscoveryAgent();
            m_DscrAgent.cancelInquiry(this);
        try {
            Thread.sleep(2000);
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        }
            try{  m_DscrAgent.startInquiry(DiscoveryAgent.GIAC, this);
        } catch (BluetoothStateException ex) {
            cont.getGui().write(/*"Problem in searching the blue tooth devices" + */"pb"+ m_LclDevice);
            ex.printStackTrace();
        }
         

    }

    /**
     *
     */
    public void run() {
       int mess = 0;
        boolean run;
        //attente de retour du mot de passe
        try {
            mess = m_Input.read();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        if (mess==1)
            run=true;
        else run=false;
       //si le mot de passe est bon, alors on attend les déblocages ( questions suivantes)
        while(run)
        {

            try {
                mess = m_Input.read();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        if (mess!=25)
            cont.deblockVote(mess);
        else run=false;
        }
    }
}



